package com.kfyang.manualgear.daoplugin.iconprovider;

import com.intellij.ide.IconProvider;
import com.intellij.lang.Language;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.PsiShortNamesCache;
import com.kfyang.manualgear.daoplugin.Constants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.YAMLFile;

import javax.swing.*;

public class DaoAndYamlIconProvider extends IconProvider {
    @Override
    public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
        if (isProperties(element)) {
            return SettingIcon.SETTING_ICON;
        }
        if (isDaoInterface(element)) {
            return DaoIcon.DAO_ICON;
        }
        if (isYamlFile(element)) {
            return YamlIcon.YAML_ICON;
        }

        return null;
    }

    private static boolean isProperties(PsiElement element) {
        if (element instanceof PsiFile psiFile) {
            return psiFile.getName().equals("dao-config.properties");
        }
        return false;
    }

    private static boolean isYamlFile(PsiElement element) {
        if (!(element instanceof YAMLFile yamlFile)) {
            return false;
        }
        String yamlFileName = yamlFile.getName();
        String className = yamlFileName.substring(0, yamlFileName.lastIndexOf('.'));

        PsiFile[] classFiles = PsiShortNamesCache.getInstance(element.getProject())
            .getFilesByName(className + ".java");
        return classFiles.length == 1;
    }

    private static boolean isDaoInterface(PsiElement element) {
        Language language = element.getLanguage();
        if (!language.isKindOf(JavaLanguage.INSTANCE)) {
            return false;
        }
        if (!(element instanceof PsiClass psiClass) || !psiClass.isInterface()) {
            return false;
        }
        return psiClass.hasAnnotation(Constants.DAO_ANNO);
    }

    private static class SettingIcon {
        public static final Icon SETTING_ICON = IconLoader.getIcon("/icons/icon_settings.png", SettingIcon.class);
    }

    private static class DaoIcon {
        public static final Icon DAO_ICON = IconLoader.getIcon("/icons/icon_dao.svg", YamlIcon.class);
    }

    private static class YamlIcon {
        public static final Icon YAML_ICON = IconLoader.getIcon("/icons/icon_yaml.png", YamlIcon.class);
    }
}
